package com.zmxstudy.gzu.controller;

import com.zmxstudy.gzu.utils.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Tag(name = "上传图片")
@Controller
@RequestMapping("/product-service/images")
public class UploadController {
    // 上传文件的基本路径
    @Value("${BaseImgLocation}")
    String BaseImgLocation;

    @ResponseBody
    @PostMapping("/upload")
    public Result<String> myUpload(@RequestParam("file") MultipartFile multipartFile) {

        //图片校验（图片是否为空,图片大小，上传的是不是图片、图片类型（例如只能上传png）等等）
        if (multipartFile == null) {
            return new Result<>(Result.ERROR_CODE, "图片为null", "");
        }
        if (multipartFile.isEmpty()) {
            return new Result<>(Result.ERROR_CODE, "上传图片不能为空", "");
        }
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println("上传文件名" + originalFilename);
        if (originalFilename == null || originalFilename.lastIndexOf(".") == -1) {
            return new Result<>(Result.ERROR_CODE, "上传图片后缀不合法", "");
        }
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        System.out.println("文件名字：" + originalFilename + " 后缀：" + extension);
        String newFileName = "images-" + UUID.randomUUID() + "." + extension;
        System.out.println("新的文件名称为-" + newFileName);
        String storageFileLoc = BaseImgLocation + File.separator + newFileName;
        System.out.println("文件地址为->" + storageFileLoc);
        try {
            multipartFile.transferTo(new File(storageFileLoc));
        } catch (IOException e) {
            System.out.println("抛出异常，上传图片失败");
        }
        return new Result<>(Result.SUCCESS_CODE, "success", "47.108.233.134:12000/product-service/static/" + newFileName);
    }

}
